package com.starblink.login.forgotpassword.emailsent.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.basic.apollo.ext.ApolloExt.findErrorCode
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.BaseApiCodeAndUrl
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.rocketreserver.SendEmailMutation
import com.starblink.rocketreserver.type.EmailVerifyRequest
import kotlinx.coroutines.launch

class ForgotPswEmailSentVM : BaseViewModel() {
    val sentEmailLiveData: MutableLiveData<String> = MutableLiveData()

    /**
     * 发送重置密码邮件
     * @param manual true表示用户手动点击try again，发送邮件
     */
    fun sendResetPswEmail(email: String?, userName: String?, manual: Boolean = false) {
        viewModelScope.launch {
            val response = SkGqlClient.skMutation(
                SendEmailMutation(
                    emailVerifyRequest = EmailVerifyRequest(
                        email = Optional.present(if (email.isNullOrEmpty()) userName else email)  // 传入邮箱或用户名
                    )
                ),
                showDefaultLoading = true
            )
            if (response?.data != null && response.data!!.sendEmail != null) {
                if(manual){
                    toast("Email sent successfully!")
                }
                sentEmailLiveData.postValue(response.data!!.sendEmail!!)
            } else if (response?.errors != null) {
                // {"errors":[{"message":"Only allowed to send three times in 24 hours","locations":[{"line":1,"column":64}],
                // "path":["sendEmail"], "extensions":{"code":"201011004","message":"Only allowed to send three times in 24 hours",
                // "classification":"DataFetchingException"}}],"data":{"sendEmail":null}}
//                response.errors!!.forEach { error ->
//                    error.extensions?.let { YYLogUtils.e(it.toString(), "dss") }
//                }
                if(response.findErrorCode(BaseApiCodeAndUrl.SEND_EMAIL_TIME_OVER_LIMIT)){
                    // 重置密码每日只能发送3次，今天已达到限制，24小时后重试
                    toast("Please try again after 24.0 hours")
                }
            }
        }
    }
}